package com.base.util;


import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.List;

/**
 * @author cjq on 20191224
 * 文件操作工具类
 */
public class FileUtil {

    /**
     * 读取excel文件每个单元格的内容
     *
     * @param file
     * @throws Exception
     */
    public static List<String> readExcelFile(File file) throws Exception {
        List<String> strings = new LinkedList<String>();
        Workbook workbook = WorkbookFactory.create(FileUtils.openInputStream(file));
        Sheet sheet = workbook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        String s = "";
        for (int i = 0; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            int lastCellNum = row.getLastCellNum();
            for (int j = 0; j <= lastCellNum; j++) {
                Cell cell = row.getCell(j);
                if (cell != null) {
                    s = StringUtils.isEmpty(String.valueOf(cell.getStringCellValue())) ? "" : String.valueOf(cell.getStringCellValue());
                }else{
                    s="";
                }
                if (s != null && !"".equals(s)) {
                    strings.add(s);
                }
            }
        }
        workbook.close();
        return strings;

    }


    /**
     * 根据路径和内容  生成txt文件
     */
    public static void writeTxtFile(List<String> content, String filePath) throws Exception {
        File file = new File(filePath);

        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        if (content != null && content.size() > 0) {
            BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
            for (String s : content) {
                String newContent = new String(s.getBytes("UTF-8"), "UTF-8");
                bw.write(newContent + "\t\n");
            }
            bw.close();
        }
    }
}

